package com.yeswater.multithread.chapter8;

import java.util.Hashtable;
import java.util.Iterator;

/**
 * author： yeswater
 * create： 2023/11/9
 * <p>
 * 目的是：验证 hashTable 不支持并发 remove 删除操作
 */
public class Run_8_2_3 {
    public static void main(String[] args) {
        Service1 service = new Service1();
        Thread1 t1 = new Thread1(service);
        Thread2 t2 = new Thread2(service);
        Thread2 t3 = new Thread2(service);
        Thread2 t4 = new Thread2(service);
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
    
    private static class Service1 {
        public Hashtable table = new Hashtable<>();
        
        public Service1() {
            for (int i = 0; i < 100000; i++) {
                table.put(Thread.currentThread().getName() + " " + (i + 1), "abc");
            }
        }
        
        public void testMethod() {
            Iterator iterator = table.keySet().iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();
                iterator.remove();
                System.out.println(table.size() + " " + Thread.currentThread().getName());
            }
        }
    }
    
    public static class Thread1 extends Thread {
        private Service1 service;
        
        public Thread1(Service1 service) {
            this.service = service;
        }
        
        @Override
        public void run() {
            service.testMethod();
        }
    }
    
    public static class Thread2 extends Thread {
        private Service1 service;
        
        public Thread2(Service1 service) {
            this.service = service;
        }
        
        @Override
        public void run() {
            service.testMethod();
        }
    }
    
}
